using System;
using System.Collections;
using System.Collections.Generic;
using LogSystem;
using UnityEngine;
using UnityEngine.U2D;
using Yoozoo.Managers.ResourceManagerV2.Runtime;
using Yoozoo.UI.YGUI;

namespace com.yoozoo.gta.Extension
{
    public class EmotePlayer : MonoBehaviour
    {  // 图集路径（例如 "Emotes/EmojiAtlas"）
        public string animationPrefix;     // 动画帧前缀（例如 "emote_200006"）
        public int startFrame;          // 起始序号（如 1）
        public int endFrame;            // 结束序号（如 4）   // 动画帧率

        private const string spriteAtlasPath = "Assets/ResourcesAssets/UI/GUI/ChatEmote.spriteatlas";
        private float frameRate = 0.1f;
        
        private Sprite[] animationSprites;  // 存储序列帧的数组
        private int currentFrame = 0;       // 当前帧
        private float timer = 0f;           // 用于计时的变量
        private YImage imageComponent;      // YImage 组件
        private ResLoader m_resLoader;

        private void Awake()
        {
            // 尝试获取 Image 组件
            imageComponent = GetComponent<YImage>();
            if (imageComponent == null)
            {
                Debug.LogError("AtlasAnimationPlayer: Image component is missing on " + gameObject.name);
            }
            if (m_resLoader == null)
            {
                m_resLoader = ResLoader.Alloc();
            }
        }
        void OnEnable()
        {
            // 重置状态：对象池复用时自动重置
            ResetAnimationState();
        }
        
        void OnDisable()
        {
            // 清理引用，避免内存泄漏或错误复用
            animationSprites = null;
        }
        
        private void OnDestroy()
        {
            if (m_resLoader != null)
            {
                m_resLoader.Recycle2Cache();
                m_resLoader = null;
            }
        }
        
        void Update()
        {
            // 判断动画是否加载完成
            if (animationSprites == null || animationSprites.Length == 0) return;

            // 帧动画播放逻辑
            timer += Time.deltaTime;
            if (timer >= frameRate)
            {
                timer = 0f;
                currentFrame++;

                if (currentFrame >= animationSprites.Length)
                {
                    currentFrame = 0; // 循环播放
                }

                // 更新当前帧
                imageComponent.sprite = animationSprites[currentFrame];
            }
        }
        
        /// <summary>
        /// 动态设置动画参数并播放动画
        /// </summary>
        /// <param name="atlasPath">图集路径（Resources下的路径）</param>
        /// <param name="prefix">Sprite前缀</param>
        /// <param name="start">起始帧</param>
        /// <param name="end">结束帧</param>
        /// <param name="rate">帧率</param>
        public void SetAnimation(string prefix, int start, int end, float rate = 0.1f)
        {
            animationPrefix = prefix;
            startFrame = start;
            endFrame = end;
            frameRate = rate;
            
            // 重新加载动画资源
            LoadAnimationSprites();
        }

        private void initSpriteDic(SpriteAtlas spriteAtlas)
        {
            int totalFrames = endFrame - startFrame + 1;
            animationSprites = new Sprite[totalFrames];

            // 筛选符合前缀和序号规则的 Sprite
            for (int i = startFrame; i <= endFrame; i++)
            {
                string frameName = $"{animationPrefix}_{i:D2}"; // 例如 "200006_01"
                Sprite sprite = spriteAtlas.GetSprite(frameName);
                if (sprite != null)
                {
                    animationSprites[i-1] = sprite;
                }
            }
                
            // 初始化首帧
            if (animationSprites.Length > 0)
            {
                imageComponent.sprite = animationSprites[0];
            }
        }

        /// <summary>
        /// 从图集中加载指定前缀和序号的 Sprite
        /// </summary>
        private void LoadAnimationSprites()
        {
            // 重置播放状态
            ResetAnimationState();
            
            if (Application.isEditor ) //&& !UnityEditor.EditorApplication.isPlaying
            {
#if UNITY_EDITOR
                SpriteAtlas spriteAtlas = UnityEditor.AssetDatabase.LoadAssetAtPath<SpriteAtlas>(spriteAtlasPath);
                initSpriteDic(spriteAtlas);
#endif
            }
            else
            {
                m_resLoader.Add2Load(spriteAtlasPath,(success, name, asset) =>
                {
                    if (!success)
                    {
                        Debug.LogErrorFormat(LogModule.Chat, "{0} not found", name);
                        return;
                    }
                    var spriteAtlas = asset as SpriteAtlas;
                    if (spriteAtlas == null)
                    {
                        Debug.LogErrorFormat(LogModule.Chat, "{0} is not SpriteAtlas ({1})", name, asset.GetType());
                        return;
                    }
                    initSpriteDic(spriteAtlas);
                });
                m_resLoader.Load();
            }
        }
        
        /// <summary>
        /// 重置动画状态，适用于对象池复用
        /// </summary>
        private void ResetAnimationState()
        {
            timer = 0f;
            currentFrame = 0;
            imageComponent.sprite = null;  // 清空当前显示的 Sprite
        }
    }
}
